<?php 
namespace Wdl\helper;

class sendHelper{

    static function rent_type($rent_type = 0){
        $r = [0=> '出售', 2=> '出租',3=> '转让'];
        if(isset($r[$rent_type]))
            return $r[$rent_type];
        return '出售';
    }
    static function add_quan_data(){
        global $_W, $_GPC; 

        $data['uniacid'] = webHelper::bindUniacid();
        $data['area'] = trim($_GPC['area']);
        $data['name'] = trim($_GPC['name']);
        $data['type'] = 2;
        $data['parent_id'] = 0;
        $data['disabled'] = 0;
        $data['orderid'] = 0;

        $uniacid = $data['uniacid'];

        $quan = pdo_fetchall("select * from " . tablename("kbwdl_area") . 
            " where uniacid='$uniacid' and name='".$data['name']."' and area='".$data['area']."' and type=2 and disabled=0  order by orderid desc ,id desc");
        if(empty($quan)){
            pdo_insert('kbwdl_area', $data);        
            return pdo_insertid();
        }
        return false;   
    }

    static function unsrialize_thumb($thumbs){
        $piclist1 = unserialize($thumbs);
        $piclist = array();
        if(is_array($piclist1)){
            foreach($piclist1 as $p){
                    $piclist[] = is_array($p)?$p['attachment']:$p;
            }
        }
        return $piclist;
    }

    static function get_loupan_item($fid)
    {
        $info =  pdo_fetch("select * from ". tablename('kbwdl_house_info')."where fid=:fid",['fid'=> $fid] );
        if($info){
            return $info;
        }
        return [];
    }

    /** 
     * 统计小区的房源数量
     * 统计小区和商圈的房源数量
     */
    static function caculte_house_nums( $house , $isdel = 0, $isquan = 0)
    {
        $area           = $house['area'];
        $village_name   = $house['village_name']; 
        $zhutype =      $house['zhutype'];
        $uniacid =      $house['uniacid'];

        if($isquan){
            if(empty($house['quan']))
                return false;

            $addon = " AND quan = :village_name";
            $village_name   = $house['quan']; 
        }else{
            if(empty($house['village_name']))
                return false;

            $addon = " AND village_name = :village_name";
        }
         
        $condition = " WHERE uniacid = :uniacid  $addon AND zhutype = :zhutype";
        $params = ['uniacid'=> $uniacid,'village_name'=> $village_name ,'zhutype'=>$zhutype];
        $sql = 'SELECT COUNT(*) FROM ' . tablename('kbwdl_house') . $condition;
        $total = pdo_fetchcolumn($sql, $params);
        $p = [
            'uniacid'=> $uniacid,
            'title'=> $area.$village_name ,
            'house_type'=>$zhutype
        ];
        $has = pdo_fetch("select * from ".tablename("kbwdl_count").
                " WHERE  uniacid = :uniacid AND title=:title AND house_type = :house_type", $p);
        $p['nums'] = $total - $isdel;
        if(!$has) 
            pdo_insert("kbwdl_count",  $p);
        else 
            pdo_update("kbwdl_count", $p, ['id'=> $has['id']]);
        
    }

    static function get_house_item($id)
    {
        global $_W, $_GPC;

        $item = pdo_fetch("SELECT * FROM " . tablename('kbwdl_house') . 
                " WHERE uniacid= :uniacid AND  id = :id", 
                array(':uniacid'=> webHelper::bindUniacid(),':id' => $id));
                
        if (empty($item)) {
           return [];
        }
        
        $params = pdo_fetchall("select * from " . tablename('kbwdl_param') . " where houseid=:id order by displayorder asc", array(':id' => $id));
        
        $item['extend_params'] = $params;
        $item['piclist'] = self::unsrialize_thumb($item['thumb_url']);
        $item['thumb_struct'] = self::unsrialize_thumb($item['thumb_struct']);
        
       
        return $item;
    }
    /**
     * 把房源数据入库
     */
    static function send_post( $id )
    {
        global $_W, $_GPC;
        if(isset($_GPC['rent_type'])){
            $data['rent_type'] = intval($_GPC['rent_type']);
        }
        // 房源图集
        if(empty($_GPC['thumbs'])){                
            $_GPC['thumbs'] = array();
        }
        //户型图
        if(empty($_GPC['thumbstruct'])){                
            $_GPC['thumbstruct'] = array();
        }
        if(!empty($_GPC['thumb'])){                
            $data['ispic'] = 1;
        }
        $data = $_GPC['data'];
        $data['uniacid'] = intval(webHelper::bindUniacid());
        $data['uid'] = $_W['uid'];
        //操作员发布的房源记录关联shopid
        if(webHelper::bindShopid()>0){
            $data['shopid'] = webHelper::bindShopid();
        }
        $data['thumb'] = $_GPC['thumb'];
        $data['endtime'] = strtotime($_GPC['endtime']);        
        $data['update_time'] = TIMESTAMP;       
        $data['description'] =  htmlspecialchars_decode($_GPC['description']);
        /*处理价格 写字楼、商铺 租金 元/㎡/月*/
        if($data['prix_unitaire'] == '元/㎡/月'){ 
            // $data['danyuan'] = $data['loyer'];
            // $data['menpai'] = $data['prix_unitaire'] ;
            // $data['loyer'] = $data['danyuan']* $data['superficie'];
            // $data['prix_unitaire'] = '元/月';
        }else{
            /*$data['danyuan'] = '';
            $data['menpai'] = '' ;*/
        }
        /*城市名*/
        if(!empty($data['city_id'])){
            $citys = webHelper::citys();
            $data['cityname'] =  isset( $citys[$data['city_id']]) ?  $citys[$data['city_id']]:'';
        }
        $data['loyer'] = sprintf('%.2f', $data['loyer']);
        $data['isonline'] = 1;
        if(!empty($_GPC['disposition']) && is_array($_GPC['disposition'])){
            $data['disposition'] = implode(',', $_GPC['disposition']); 
        }else{
            $data['disposition'] = "";
        }
        /**设置属性 */
        $tjw = ['istop','ishot','isjingpin','show_jiaji','show_you','show_hight'];
        foreach($tjw as $f){
             $data[$f] = isset($data[$f]) && $data[$f]==1 ? 1 :0;
        }
        
        /*生意转让的时候合并行业和经营类型*/
        if(!empty($_GPC['hangye']) || !empty($_GPC['jingyin'])){
            $data['prule'] = $_GPC['hangye'].",".$_GPC['jingyin'];
        }
         //房源图片
        if(is_array($_GPC['thumbs'])){
            $data['thumb_url'] = serialize($_GPC['thumbs']);
        }
        //户型图
        if(is_array($_GPC['thumbstruct'])){
            $data['thumb_struct'] = serialize($_GPC['thumbstruct']);
        }
        /*处理管理员，如果 有管理员就覆盖联系人*/
        if($data['broker_id']>0){
            $bro  = pdo_fetch("select * from ".tablename("kbwdl_broker")." where id='".$data['broker_id']."'");
            $data['broker_name'] = $bro['nickname'];
           /* $data['publish_name'] = $bro['nickname'];
            $data['linkphone'] = $bro['mobile'];*/
        }else{
            unset($data['broker_id']);
        }
        if(isset($_GPC['mapinfo'])){
            $data['mapinfo'] = $_GPC['mapinfo']['lng'].",". $_GPC['mapinfo']['lat'];
        }
        if($data['zhutype'] < 4){
            //把小区数据录入
            $data['village_id'] = VillageHelper::save_village($data['area'], $data['village_name']);

        }
        
        /*新增和修改保存数据*/
        if (empty($id)) {
                $data['refresh_time'] = TIMESTAMP;
                $data['add_time'] = TIMESTAMP;
                pdo_insert('kbwdl_house', $data);
                $id = pdo_insertid();
                
                
        } else {
                $old = pdo_fetch("select * from ".tablename('kbwdl_house'). " WHERE id=:id AND uniacid=:uniacid", ['id' => $id,'uniacid'=> $data['uniacid']]) ;
                pdo_update('kbwdl_house', $data, array('id' => $id,'uniacid'=> $data['uniacid']));
                
               
        }
        
        //把楼盘数据存入
        sendHelper::save_house_info($id, $_GPC['loupan']);

        /**
         * 统计小区房源数量
         */
       
        sendHelper::caculte_house_nums( $data ); //统计小区
        sendHelper::caculte_house_nums( $data,0 ,1 ); //统计商圈
        if(!empty($old)){
            //修改的时候重新统计旧的小区
            if($old['quan'] != $data['quan']){
                sendHelper::caculte_house_nums( $old,0 ,1 ); //统计商圈 
            }
            if($old['village_name'] != $data['village_name']){
                sendHelper::caculte_house_nums( $old  ); //统计商圈 
            }
        }
         
        
        // if($data['village_id']>0){
        //     $vid = intval($data['village_id']);
        //     $total = pdo_fetchcolumn("select count(*) as total from ".tablename("kbwdl_house")." where village_id=$vid and uniacid='{$_W['uniacid']}'");
        //     pdo_update('kbwdl_area', array('zhunum'=>$total), array('id'=>$vid));
        // }
        /*
         * 处理自定义参数
         */
        $param_ids =   isset($_POST['param_id']) ? $_POST['param_id']:[];
        $param_titles = isset($_POST['param_title']) ? $_POST['param_title']:[] ;
        $param_values = isset($_POST['param_value']) ? $_POST['param_value']:[] ;
        
        $len = count($param_ids);
        $paramids = array();
        for ($k = 0; $k < $len; $k++) {
                $param_id = "";
                $get_param_id = $param_ids[$k];
                $a = array(
                        "title" => $param_titles[$k],
                        "value" => $param_values[$k],
                        "displayorder" => $k,
                        "houseid" => $id,
                );
                if (!is_numeric($get_param_id)) {
                        pdo_insert("kbwdl_param", $a);
                        $param_id = pdo_insertid();
                } else {
                        pdo_update("kbwdl_param", $a, array('id' => $get_param_id));
                        $param_id = $get_param_id;
                }
                $paramids[] = $param_id;
        }
        if (count($paramids) > 0) {
                pdo_query("delete from " . tablename('kbwdl_param') . " where houseid=$id and id not in ( " . implode(',', $paramids) . ")");
        }
        else{
                pdo_query("delete from " . tablename('kbwdl_param') . " where houseid=$id");
        } 
 
        return $id;
    }

    static function save_house_info($fid, $data )
    {
       $data['fid'] = $fid;
       $info =  pdo_fetch("select * from ". tablename('kbwdl_house_info')."where fid=:fid",['fid'=> $fid] );
       if($info){
            
            pdo_update("kbwdl_house_info", $data, ['id'=> $info['id']]);
       }else{
             
            pdo_insert("kbwdl_house_info", $data);
       }
       return true;
    }
}